﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using  RWLibrary.Logic.Graph;
namespace RWLibrary.Logic.Queries
{
    using Graph;
    public class NecessaryValueQuery : ValueQuery
    {
        public NecessaryValueQuery(Graph graph) : base(graph)
        {
        }

        public override bool Excecute()
        {
            Dictionary<Node, int> actualPositions = Graph.Nodes.Where(n => Pi.Test(n.State)).ToDictionary(n => n, n => 0);

            foreach (var action in Actions)
            {
                Dictionary<Node, int> nextPositions = new Dictionary<Node, int>();
                foreach (var actualPosition in actualPositions)
                {
                    foreach(var e in  actualPosition.Key.Connections.Where(e => e.Key.Name == action))
                    {
                        if (nextPositions.ContainsKey(e.Value))
                        {
                            if (nextPositions[e.Value] < actualPosition.Value + e.Key.Cost)
                                nextPositions[e.Value] = actualPosition.Value + e.Key.Cost;
                        }
                        else
                        {
                            nextPositions.Add(e.Value, actualPosition.Value + e.Key.Cost);
                        }
                        if (nextPositions[e.Value] > Cost)
                            return false;
                    }
                }
                actualPositions = nextPositions;
            }
            foreach (var position in actualPositions)
                if(!Alpha.Test(position.Key.State))
                    return false;
            return true;
        }
    }
}
